package com.zhao.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.entity.EduSubject;
import com.zhao.entity.execl.SubjectExecl;
import com.zhao.exceptionHandel.GuliException;
import com.zhao.service.EduSubjectService;

/**
 *          因为SubjectListen在EduSubjectServiceImpl类中是new处来的,所以SubjectListen无法在spring容器中创建
 *          因此也就无法自动注入其它类，只能自己手动注入
 */
public class SubjectListen extends AnalysisEventListener<SubjectExecl> {
    private EduSubjectService subjectService;
    public SubjectListen() {
    }
    public SubjectListen(EduSubjectService subjectService) {
        this.subjectService=subjectService;
    }

    /**
     *
     * @param subjectExecl
     * @param analysisContext
     */
    @Override
    public void invoke(SubjectExecl subjectExecl, AnalysisContext analysisContext) {
        //先判断subjectExecl是否为空
        if (subjectExecl == null){
            throw new GuliException(20001,"subjectExecl为空");
        }
        //先判断一级分类有没有重复
        EduSubject eduSubject = existOneSubject(subjectService, subjectExecl.getOneSubject());
        if(eduSubject==null){
            eduSubject=new EduSubject();
            eduSubject.setParentId("0");
            //一级分类名称
            eduSubject.setTitle(subjectExecl.getOneSubject());
            subjectService.save(eduSubject);
        }

        //先获取二级分类的parent_id
        String pid=eduSubject.getId();
        //再判断二级分类有没有重复
        EduSubject eduSubject1 = existTwoSubject(subjectService, subjectExecl.getOneSubject(),pid);
        if(eduSubject1==null){
            System.out.println("jinlial --------------------------");
            eduSubject1=new EduSubject();
            eduSubject1.setParentId(pid);
            //二级分类的名称
            eduSubject1.setTitle(subjectExecl.getTwoSubject());
            subjectService.save(eduSubject1);
        }
    }

    //先判断一级分类有没有
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject>wrapper=new QueryWrapper<>();
        wrapper.eq("title",name).eq("parent_id",0);
        EduSubject subject = subjectService.getOne(wrapper);
        return subject;
    }

    //判断二级分类有没有
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject>wrapper=new QueryWrapper<>();
        wrapper.eq("title",name).eq("parent_id",pid);
        EduSubject subject = subjectService.getOne(wrapper);
        return subject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
